<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Number;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Response;

class NumberController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Number(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('number');
            $grid->column('type');
            $grid->column('status');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Number(), function (Show $show) {
            $show->field('id');
            $show->field('number');
            $show->field('type');
            $show->field('status');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Number(), function (Form $form) {
            $form->display('id');
            $form->radio('type')->options(admin_trans('user.options.type'))->default('1');
            $form->text('type');
        });
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function numberList(Request $request)
    {
        $type = $request->get('type');

        $number = \App\Models\Number::where('type', $type)->get()->toArray();

        foreach ($number as $key => &$value) {
            $user = User::where('number_id', $value['id'])->first();

            if ($user) {
                if ($user->days_remaining > 7) {
                    $value['user_status'] = 1;
                } elseif ($user->days_remaining < 7 && $user->days_remaining > 0) {
                    $value['user_status'] = 2;
                } else {
                    $value['user_status'] = 3;
                }

                $value['user_name'] = $user->name;
                $value['days_remaining'] = $user->days_remaining;
                $value['user_id'] = $user->id;
            } else {
                $value['user_status'] = 0;
            }
        }

        return json_encode($number);
    }
}
